package array;

import java.lang.reflect.Array;
import java.util.Arrays;

public class leetCode807_advantageCount {
    public int[] advantageCount(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        int n = nums1.length;
        int[][] sortB = new int[nums2.length][2];
        for (int i = 0; i < nums2.length; i++) {
            sortB[i] = new int[]{nums2[i],i};
        }
        Arrays.sort(sortB,(a,b) -> a[0] - b[0]);

        int[] res = new int[n];
        int left = 0;
        int right = n - 1;

        for (int i = 0; i < n; i++) {
            if(nums1[i] <= sortB[left][0]){
                res[sortB[right][1]] = nums1[i];
                right--;
            }else{
                res[sortB[left][1]] = nums1[i];
                left++;
            }
        }
        return res;
    }
}
